package com.jolink.omiis.wechat.api.impl;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jolink.omiis.wechat.api.IMaterialApi;
import com.jolink.omiis.wechat.message.type.MediaType;

public class MaterialApiImpl extends WeChatApiBaseService implements IMaterialApi {

	private static Logger logger = LoggerFactory.getLogger(MaterialApiImpl.class);

	private String uploadTempMaterial(String appId, String filePath, String mediaType) {
		long t1 = System.currentTimeMillis();
		File materialFile = new File(filePath);
		if (!materialFile.exists()) {
			return null;
		}
		logger.info("上传临时素材至腾讯服务器，appId：{}，filePath：{}，mediaType：{}。", appId, filePath, mediaType);
		String baseUri = MEDIA_UPLOAD;
		String access_token = getCompanyAuthorizerAccessToken(appId);
		String reqParams = "access_token=" + access_token + "&type=" + mediaType;
		String result = (String) executePostFile(baseUri, reqParams, filePath);
		long t2 = System.currentTimeMillis();
		logger.info("上传临时素材至腾讯服务器完成，返回结果：{}，耗时：{}毫秒。", result, (t2 - t1));
		return result;
	}

	@Override
	public String uploadImage(String appid, String filename) {
		return uploadTempMaterial(appid, filename, MediaType.IMAGE.getValue());
	}

	@Override
	public Map<String, String> downloadTempMaterial(String appId, String mediaId) {
		long t1 = System.currentTimeMillis();
		logger.info("从腾讯服务器下载临时素材，素材信息，appId：{}，mediaId：{}。", appId, mediaId);
		Map<String, String> resultMap = new HashMap<String, String>();
		String baseUri = MEDIA_GET;
		String access_token = getCompanyAuthorizerAccessToken(appId);
		String reqParams = "access_token=" + access_token + "&media_id=" + mediaId;
		resultMap.putAll(executeGet(baseUri, reqParams));
		long t2 = System.currentTimeMillis();
		logger.info("从腾讯服务器下载临时素材完成，结果：{}，耗时：{}毫秒。", resultMap, (t2 - t1));
		return resultMap;
	}

	@Override
	public String uploadVideo(String appid, String filename) {
		return uploadTempMaterial(appid, filename, MediaType.VIDEO.getValue());
	}

	@Override
	public String uploadVoice(String appid, String filename) {
		return uploadTempMaterial(appid, filename, MediaType.VOICE.getValue());
	}

	@Override
	public String uploadThumb(String appid, String filename) {
		return uploadTempMaterial(appid, filename, MediaType.THUMB.getValue());
	}
}
